using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using RawRestructure.Enums;
using RawRestructure.Models;
using RawRestructure.Models.DataStructures;
using RawRestructure.Services.Interfaces;
using Avalonia.Platform.Storage;

namespace RawRestructure.ViewModels;

/// <summary>
/// 主窗口视图模型
/// </summary>
public partial class MainWindowViewModel : ViewModelBase
{
    private readonly IFileAnalysisService _fileAnalysisService;
    private readonly IConfigService _configService;
    private readonly ITcpClientService _tcpClientService;
    private readonly ILogger<MainWindowViewModel> _logger;
    
    // 工作站连接信息（不再暴露为公开属性）
    private string _workstationIp;
    private int _workstationPort;

    public MainWindowViewModel(IFileAnalysisService fileAnalysisService, IConfigService configService, ITcpClientService tcpClientService, ILogger<MainWindowViewModel> logger)
    {
        _fileAnalysisService = fileAnalysisService;
        _configService = configService;
        _tcpClientService = tcpClientService;
        _logger = logger;
        
        LogMessages = new ObservableCollection<string>();
        AddLogMessage("应用程序已启动");
        
        // 获取工作站配置
        _workstationIp = _configService.GetWorkstationIp();
        _workstationPort = _configService.GetWorkstationPort();
        
        // 获取批量发送配置
        _batchSize = _configService.GetBatchSize();
        _sendIntervalMs = _configService.GetSendIntervalMs();
        _mockDelayMs = _configService.GetMockDelayMs();
        
        // 注册TCP连接状态变化事件
        _tcpClientService.ConnectionStateChanged += OnConnectionStateChanged;
        
        // 注册应用程序退出事件，确保在退出时断开连接
        if (Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IControlledApplicationLifetime lifetime)
        {
            lifetime.Exit += OnApplicationExit;
        }
        
        // 启动时自动连接工作站
        _ = ConnectToWorkstation();
    }
    
    /// <summary>
    /// 连接状态变化事件处理
    /// </summary>
    private void OnConnectionStateChanged(object? sender, bool isConnected)
    {
        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
        {
            IsConnected = isConnected;
            ConnectionStatus = isConnected ? "已连接" : "未连接";
            
            if (isConnected)
            {
                AddLogMessage("已连接到工作站");
            }
            else
            {
                AddLogMessage("已断开与工作站的连接");
            }
        });
    }
    
    /// <summary>
    /// 应用程序退出时的处理
    /// </summary>
    private void OnApplicationExit(object? sender, EventArgs e)
    {
        // 如果已连接，则断开连接
        if (IsConnected)
        {
            // 使用同步方法断开连接，确保在应用关闭前完成
            DisconnectFromWorkstationSync();
        }
        
        // 注销事件处理器
        if (Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IControlledApplicationLifetime lifetime)
        {
            lifetime.Exit -= OnApplicationExit;
        }
        
        // 注销TCP连接状态变化事件
        _tcpClientService.ConnectionStateChanged -= OnConnectionStateChanged;
    }

    #region 属性

    /// <summary>
    /// 选中的目录路径
    /// </summary>
    [ObservableProperty]
    private string selectedDirectory = string.Empty;

    /// <summary>
    /// 分析结果
    /// </summary>
    [ObservableProperty]
    private ImageInfo? analysisResult;

    /// <summary>
    /// 曝光模式显示文本
    /// </summary>
    [ObservableProperty]
    private string expModeDisplayName = "";

    /// <summary>
    /// 连接状态
    /// </summary>
    [ObservableProperty]
    private string connectionStatus = "未连接";

    /// <summary>
    /// 是否已连接
    /// </summary>
    [ObservableProperty]
    private bool isConnected = false;

    /// <summary>
    /// 发送数量
    /// </summary>
    [ObservableProperty]
    private int sendCount = 0;

    /// <summary>
    /// 是否正在分析
    /// </summary>
    [ObservableProperty]
    private bool isAnalyzing = false;

    /// <summary>
    /// 日志消息
    /// </summary>
    public ObservableCollection<string> LogMessages { get; }

    #endregion

    #region 命令

    /// <summary>
    /// 浏览文件夹命令
    /// </summary>
    [RelayCommand]
    private async Task BrowseFolder()
    {
        try
        {
            // 打开文件夹选择对话框
            var dialog = new OpenFolderDialog
            {
                Title = "选择文件夹"
            };
            
            // 获取当前应用程序的主窗口
            var mainWindow = Avalonia.Application.Current.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop 
                ? desktop.MainWindow
                : null;
                
            // 显示对话框
            var selectedFolder = await dialog.ShowAsync(mainWindow);
            
            // 如果用户选择了文件夹
            if (!string.IsNullOrEmpty(selectedFolder))
            {
                SelectedDirectory = selectedFolder;
                await AnalyzeDirectoryAsync();
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "浏览文件夹时发生错误");
            AddLogMessage($"浏览文件夹失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 分析目录
    /// </summary>
    private async Task AnalyzeDirectoryAsync()
    {
        if (string.IsNullOrEmpty(SelectedDirectory))
            return;

        try
        {
            IsAnalyzing = true;
            AddLogMessage($"开始分析目录: {SelectedDirectory}");

            AnalysisResult = await _fileAnalysisService.AnalyzeDirectoryAsync(SelectedDirectory);
            
            if (AnalysisResult != null)
            {
                SendCount = AnalysisResult.MinCount;
                AddLogMessage($"分析完成 - 正位: {AnalysisResult.PaCount}, 侧位: {AnalysisResult.LatCount}, 模式: {AnalysisResult.CurrentImageMode}");
                
                if (AnalysisResult.HasConfigFile && AnalysisResult.Config != null)
                {
                    ExpModeDisplayName = AnalysisResult.Config.GetExpModeDisplayName();
                    AddLogMessage($"发现配置文件 - 曝光模式: {ExpModeDisplayName}");
                    
                    // 显示提示对话框
                    await ShowMessageBoxAsync(
                        "请注意ZK应该处于曝光页面并且曝光模式和软件显示的一致", 
                        "重要提示");
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "分析目录时发生错误");
            AddLogMessage($"分析目录失败: {ex.Message}");
        }
        finally
        {
            IsAnalyzing = false;
        }
    }

    /// <summary>
    /// 连接工作站命令（内部使用，不再暴露为命令）
    /// </summary>
    private async Task ConnectToWorkstation()
    {
        try
        {
            if (_tcpClientService.IsConnected)
            {
                _logger.LogDebug("已连接到工作站，无需重复连接");
                return;
            }
            
            AddLogMessage($"尝试连接工作站: {_workstationIp}:{_workstationPort}");
            
            bool result = await _tcpClientService.ConnectAsync(_workstationIp, _workstationPort);
            
            if (!result)
            {
                AddLogMessage("连接失败");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "连接工作站时发生错误");
            AddLogMessage($"连接失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 断开连接（内部使用，不再暴露为命令）
    /// </summary>
    private async Task DisconnectFromWorkstation()
    {
        try
        {
            if (!_tcpClientService.IsConnected)
            {
                _logger.LogDebug("未连接到工作站，无需断开");
                return;
            }
            
            AddLogMessage("正在断开与工作站的连接");
            
            await _tcpClientService.DisconnectAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "断开连接时发生错误");
            AddLogMessage($"断开连接失败: {ex.Message}");
        }
    }
    
    /// <summary>
    /// 同步断开连接（用于应用关闭时）
    /// </summary>
    private void DisconnectFromWorkstationSync()
    {
        try
        {
            if (!_tcpClientService.IsConnected)
            {
                return;
            }
            
            _logger.LogInformation("应用程序关闭，断开与工作站的连接");
            
            _tcpClientService.DisconnectSync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "应用关闭时断开连接发生错误");
        }
    }

    /// <summary>
    /// 发送数据命令
    /// </summary>
    [RelayCommand]
    private async Task SendData()
    {
        try
        {
            if (!IsConnected)
            {
                AddLogMessage("请先连接工作站");
                return;
            }

            if (AnalysisResult == null)
            {
                AddLogMessage("请先选择并分析文件夹");
                return;
            }

            AddLogMessage("开始发送数据...");
            
            // 批处理策略
            bool useBatchStrategy = false;
            ExpMode expMode = ExpMode.SIGNAL; // 默认值
            
            if (AnalysisResult.HasConfigFile && AnalysisResult.Config != null)
            {
                expMode = AnalysisResult.Config.GetExpMode();
                AddLogMessage($"检测到曝光模式: {expMode}");
                
                // 根据expmode决定是否使用分批策略
                useBatchStrategy = expMode == ExpMode.FLUORO || expMode == ExpMode.ACQUISITION;
                
                // 如果sendCount为0，自动设置为最大值
                if (SendCount == 0)
                {
                    SendCount = AnalysisResult.MinCount;
                }
            }
            
            try
            {
                if (useBatchStrategy && SendCount > _batchSize)
                {
                    // 使用批处理策略，计算批次
                    var batches = CalculateBatches(SendCount, StartIndex);
                    AddLogMessage($"将分 {batches.Count - 1} 批发送数据，每批最多 {_batchSize} 张图像，然后发送最终确认");
                    
                    for (int i = 0; i < batches.Count; i++)
                    {
                        var (batchStartIndex, batchLength, isLastBatch) = batches[i];
                        
                        if (isLastBatch)
                        {
                            AddLogMessage($"发送最终确认: 索引=1, 总数量={batchLength}");
                        }
                        else
                        {
                            AddLogMessage($"发送第 {i + 1}/{batches.Count - 1} 批数据: 索引={batchStartIndex}, 数量={batchLength}");
                        }
                        
                        await SendBatch(batchStartIndex, batchLength, isLastBatch, SendCount);
                        
                        // 每批之间需要间隔（包括最终确认前）
                        if (i < batches.Count - 1 && _sendIntervalMs > 0)
                        {
                            string nextStage = (i == batches.Count - 2) ? "最终确认" : "下一批";
                            AddLogMessage($"等待 {_sendIntervalMs}ms 后发送{nextStage}...");
                            await Task.Delay(_sendIntervalMs);
                        }
                    }
                }
                else
                {
                    // 不分批或仅发送一批
                    AddLogMessage($"单批发送: 索引={StartIndex}, 数量={SendCount}");
                    await SendBatch(StartIndex, SendCount, true, SendCount);
                }
                
                AddLogMessage("数据发送完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "发送数据时发生错误");
                AddLogMessage($"发送数据失败: {ex.Message}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发送数据时发生错误");
            AddLogMessage($"发送数据失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 清除日志命令
    /// </summary>
    [RelayCommand]
    private void ClearLogs()
    {
        LogMessages.Clear();
        AddLogMessage("日志已清除");
    }

    #endregion

    #region 辅助方法

    // 批量发送配置参数
    private readonly int _batchSize; // 每批发送数量
    private readonly int _sendIntervalMs; // 发送间隔(毫秒)
    private readonly int _mockDelayMs; // 模拟发送延迟(毫秒)
    
    // 固定起始索引值（移除UI控件后）
    private const int StartIndex = 1;
    
    /// <summary>
    /// 添加日志消息
    /// </summary>
    /// <param name="message">消息内容</param>
    private void AddLogMessage(string message)
    {
        Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
        {
            var timestamp = DateTime.Now.ToString("HH:mm:ss");
            LogMessages.Add($"[{timestamp}] {message}");
            
            // 限制日志数量，避免内存占用过大
            while (LogMessages.Count > 100)
            {
                LogMessages.RemoveAt(0);
            }
        });
    }
    
    /// <summary>
    /// 计算分批信息
    /// </summary>
    /// <param name="totalCount">总数量</param>
    /// <param name="startIndex">起始索引</param>
    /// <returns>批次信息列表</returns>
    private List<(int startIndex, int length, bool isLastBatch)> CalculateBatches(int totalCount, int startIndex)
    {
        var batches = new List<(int startIndex, int length, bool isLastBatch)>();
        int currentStart = startIndex;
        int remaining = totalCount;
        
        // 第一阶段：使用XXRawSavePath分批发送所有图像
        while (remaining > 0)
        {
            int currentBatchSize = Math.Min(_batchSize, remaining);
            
            // 所有批次都不是最后批次（在第一阶段）
            batches.Add((currentStart, currentBatchSize, false));
            
            currentStart += currentBatchSize;
            remaining -= currentBatchSize;
        }
        
        // 第二阶段：添加最终确认批次，使用XXLastRawSavePath
        // rawNumStart从1开始，rawLength为总数量
        batches.Add((startIndex, totalCount, true));
        
        return batches;
    }
    
    /// <summary>
    /// 发送单批数据
    /// </summary>
    /// <param name="startIndex">起始索引</param>
    /// <param name="length">长度</param>
    /// <param name="isLastBatch">是否为最后一批</param>
    /// <param name="totalLength">总长度（用于最后一批发送）</param>
    /// <returns>异步任务</returns>
    private async Task SendBatch(int startIndex, int length, bool isLastBatch, int totalLength = 0)
    {
        try
        {
            string dirName = AnalysisResult!.DirectoryName;
            
            // 确定CommandType
            CommandType commandType;
            
            if (AnalysisResult.HasConfigFile && AnalysisResult.Config != null)
            {
                var expMode = AnalysisResult.Config.GetExpMode();
                
                switch (expMode)
                {
                    case ExpMode.FLUORO:
                        commandType = isLastBatch ? CommandType.FluoroLastRawSavePath : CommandType.FluoroRawSavePath;
                        break;
                    case ExpMode.ACQUISITION:
                        commandType = isLastBatch ? CommandType.SequenceLastRawSavePath : CommandType.SequenceRawSavePath;
                        break;
                    case ExpMode.SIGNAL:
                    case ExpMode.SLOT:
                    case ExpMode.TOMO:
                    default:
                        commandType = CommandType.LastRawSavePath;
                        break;
                }
            }
            else
            {
                // 如果没有配置文件，使用默认命令类型
                commandType = CommandType.LastRawSavePath;
            }
            
            // 获取是否为组保存
            bool isPairMode = AnalysisResult.IsPairMode;
            AddLogMessage($"组保存模式: {(isPairMode ? "是" : "否")}");
            
            // 创建结构体数据
            byte[] structBytes;
            
            switch (commandType)
            {
                case CommandType.LastRawSavePath:
                    var lastRawSavePath = LastRawSavePath.Create(
                        (ushort)startIndex, 
                        (ushort)length, 
                        isPairMode, // 根据IsPairMode设置
                        dirName
                    );
                    structBytes = lastRawSavePath.ToByteArray();
                    AddLogMessage($"发送批次数据: LastRawSavePath, 索引={lastRawSavePath.rawNumStart}, 数量={lastRawSavePath.rawLength}, 组保存={lastRawSavePath.rawPair}");
                    break;
                    
                case CommandType.FluoroRawSavePath:
                    var fluoroRawSavePath = FluoroRawSavePath.Create(
                        (ushort)startIndex, 
                        (ushort)length, 
                        isPairMode, // 根据IsPairMode设置
                        dirName
                    );
                    structBytes = fluoroRawSavePath.ToByteArray();
                    AddLogMessage($"发送批次数据: FluoroRawSavePath, 索引={fluoroRawSavePath.rawNumStart}, 数量={fluoroRawSavePath.rawLength}, 组保存={fluoroRawSavePath.rawPair}");
                    break;
                    
                case CommandType.FluoroLastRawSavePath:
                    // 最终确认批次：rawNumStart固定为1，rawLength为总数量
                    var fluoroLastRawSavePath = FluoroLastRawSavePath.Create(
                        1, // rawNumStart固定为1
                        (ushort)(totalLength > 0 ? totalLength : length), 
                        isPairMode, // 根据IsPairMode设置
                        dirName
                    );
                    structBytes = fluoroLastRawSavePath.ToByteArray();
                    AddLogMessage($"发送最终确认数据: FluoroLastRawSavePath, 索引=1, 数量={fluoroLastRawSavePath.rawLength}(总长度), 组保存={fluoroLastRawSavePath.rawPair}");
                    break;
                    
                case CommandType.SequenceRawSavePath:
                    var seqRawSavePath = SequenceRawSavePath.Create(
                        (ushort)startIndex, 
                        (ushort)length, 
                        isPairMode, // 根据IsPairMode设置
                        dirName
                    );
                    structBytes = seqRawSavePath.ToByteArray();
                    AddLogMessage($"发送批次数据: SequenceRawSavePath, 索引={seqRawSavePath.rawNumStart}, 数量={seqRawSavePath.rawLength}, 组保存={seqRawSavePath.rawPair}");
                    break;
                    
                case CommandType.SequenceLastRawSavePath:
                    // 最终确认批次：rawNumStart固定为1，rawLength为总数量  
                    var seqLastSavePath = SequenceLastRawSavePath.Create(
                        1, // rawNumStart固定为1
                        (ushort)(totalLength > 0 ? totalLength : length), 
                        isPairMode, // 根据IsPairMode设置
                        dirName
                    );
                    structBytes = seqLastSavePath.ToByteArray();
                    AddLogMessage($"发送最终确认数据: SequenceLastRawSavePath, 索引=1, 数量={seqLastSavePath.rawLength}(总长度), 组保存={seqLastSavePath.rawPair}");
                    break;
                    
                default:
                    // 如果未知的CommandType，则使用默认结构体
                    var defaultPath = LastRawSavePath.Create(
                        (ushort)startIndex, 
                        (ushort)length, 
                        isPairMode, // 根据IsPairMode设置
                        dirName
                    );
                    structBytes = defaultPath.ToByteArray();
                    AddLogMessage($"发送批次数据: 默认结构体, 索引={defaultPath.rawNumStart}, 数量={defaultPath.rawLength}, 组保存={defaultPath.rawPair}");
                    break;
            }
            
            // 创建数据包
            var packet = TcpPacket.Create(commandType, structBytes);
            byte[] packetBytes = packet.ToByteArray();
            
            // 记录CommandType和数据的十六进制表示
            AddLogMessage($"批次命令类型: {commandType} (0x{(byte)commandType:X2})");
            AddLogMessage($"批次发送数据: {ByteArrayToHexString(packetBytes)}");
            
            // 发送数据包
            bool result = await _tcpClientService.SendPacketAsync(packet);
            
            if (result)
            {
                if (isLastBatch)
                {
                    AddLogMessage($"最终确认发送成功: 总数量={length}");
                }
                else
                {
                    AddLogMessage($"批次数据发送成功: 索引={startIndex}, 数量={length}");
                }
            }
            else
            {
                AddLogMessage($"批次数据发送失败: 索引={startIndex}, 数量={length}");
                throw new Exception("发送数据失败");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发送批次数据时发生错误");
            AddLogMessage($"发送批次数据失败: {ex.Message}");
            throw; // 重新抛出异常，让调用者处理
        }
    }
    
    /// <summary>
    /// 获取命令类型
    /// </summary>
    /// <returns>命令类型</returns>
    private CommandType GetCommandType()
    {
        // 根据曝光模式选择合适的CommandType
        if (AnalysisResult?.HasConfigFile == true && AnalysisResult.Config != null)
        {
            var expMode = AnalysisResult.Config.GetExpMode();
            bool isLast = StartIndex + SendCount >= AnalysisResult.MinCount;
            
            switch (expMode)
            {
                case ExpMode.FLUORO:
                    return isLast ? CommandType.FluoroLastRawSavePath : CommandType.FluoroRawSavePath;
                case ExpMode.ACQUISITION:
                    return isLast ? CommandType.SequenceLastRawSavePath : CommandType.SequenceRawSavePath;
                case ExpMode.SIGNAL:
                case ExpMode.SLOT:
                case ExpMode.TOMO:
                default:
                    return CommandType.LastRawSavePath;
            }
        }
        
        // 默认命令类型
        return CommandType.LastRawSavePath;
    }
    
    /// <summary>
    /// 将字节数组转换为十六进制字符串
    /// </summary>
    /// <param name="bytes">字节数组</param>
    /// <returns>十六进制字符串</returns>
    private string ByteArrayToHexString(byte[] bytes)
    {
        if (bytes == null || bytes.Length == 0)
            return string.Empty;
        
        var sb = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            // 每16个字节换行
            if (i > 0 && i % 16 == 0)
                sb.Append("\n");
            // 每8个字节添加额外空格
            else if (i > 0 && i % 8 == 0)
                sb.Append("  ");
            // 每个字节之间添加空格
            else if (i > 0)
                sb.Append(" ");
            
            sb.Append(bytes[i].ToString("X2"));
        }
        
        return sb.ToString();
    }

    /// <summary>
    /// 显示消息对话框
    /// </summary>
    /// <param name="message">消息</param>
    /// <param name="title">标题</param>
    /// <returns>异步任务</returns>
    private async Task ShowMessageBoxAsync(string message, string title)
    {
        try
        {
            // 获取当前应用程序的主窗口
            var mainWindow = Avalonia.Application.Current.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop 
                ? desktop.MainWindow
                : null;
                
            if (mainWindow != null)
            {
                // 创建告警图标
                var warningIcon = new PathIcon
                {
                    Data = StreamGeometry.Parse("M12,1 L22,21 L2,21 Z M12,6 L12,14 M12,16 L12,18"),
                    Foreground = new SolidColorBrush(Colors.OrangeRed),
                    Width = 40,
                    Height = 40
                };

                // 创建无边框对话框
                var dialog = new Window
                {
                    Title = title,
                    Width = 400,
                    Height = 200,
                    WindowStartupLocation = WindowStartupLocation.CenterOwner,
                    SystemDecorations = SystemDecorations.None,
                    Background = new SolidColorBrush(Colors.Transparent),
                    TransparencyLevelHint = new WindowTransparencyLevel[] { WindowTransparencyLevel.Transparent }
                };

                // 创建主容器
                var mainPanel = new Border
                {
                    Background = new SolidColorBrush(Colors.White),
                    CornerRadius = new CornerRadius(8),
                    BoxShadow = new BoxShadows(new BoxShadow
                    {
                        OffsetX = 3,
                        OffsetY = 3,
                        Blur = 10,
                        Spread = 0,
                        Color = Color.FromArgb(128, 0, 0, 0)
                    }),
                    Padding = new Thickness(20),
                    Child = new Grid
                    {
                        RowDefinitions = new RowDefinitions("Auto,*,Auto"),
                        ColumnDefinitions = new ColumnDefinitions("Auto,*"),
                    }
                };

                // 将控件添加到Grid
                var grid = (Grid)mainPanel.Child!;

                // 添加标题
                grid.Children.Add(new TextBlock
                {
                    Text = title,
                    FontWeight = FontWeight.Bold,
                    FontSize = 16,
                    Margin = new Thickness(0, 0, 0, 10),
                    Foreground = new SolidColorBrush(Colors.Black)
                });
                Grid.SetRow(grid.Children[0], 0);
                Grid.SetColumn(grid.Children[0], 0);
                Grid.SetColumnSpan(grid.Children[0], 2);

                // 添加警告图标
                grid.Children.Add(warningIcon);
                Grid.SetRow(grid.Children[1], 1);
                Grid.SetColumn(grid.Children[1], 0);
                Grid.SetRowSpan(grid.Children[1], 1);

                // 添加消息文本
                grid.Children.Add(new TextBlock
                {
                    Text = message,
                    TextWrapping = TextWrapping.Wrap,
                    VerticalAlignment = VerticalAlignment.Center,
                    Margin = new Thickness(10, 0, 0, 0),
                    Foreground = new SolidColorBrush(Colors.Black)
                });
                Grid.SetRow(grid.Children[2], 1);
                Grid.SetColumn(grid.Children[2], 1);

                // 添加确定按钮
                var buttonPanel = new StackPanel
                {
                    Orientation = Orientation.Horizontal,
                    HorizontalAlignment = HorizontalAlignment.Right,
                    Margin = new Thickness(0, 10, 0, 0)
                };

                var okButton = new Button
                {
                    Content = "确定",
                    Padding = new Thickness(20, 8, 20, 8),
                    Background = new SolidColorBrush(Color.FromRgb(0, 120, 212)),
                    Foreground = new SolidColorBrush(Colors.White),
                    CornerRadius = new CornerRadius(4)
                };

                buttonPanel.Children.Add(okButton);
                grid.Children.Add(buttonPanel);
                Grid.SetRow(grid.Children[3], 2);
                Grid.SetColumn(grid.Children[3], 0);
                Grid.SetColumnSpan(grid.Children[3], 2);

                // 为按钮添加点击事件
                okButton.Click += (s, e) => dialog.Close();

                // 为容器边缘添加拖动功能
                mainPanel.PointerPressed += (s, e) =>
                {
                    if (e.Source == mainPanel)
                    {
                        dialog.BeginMoveDrag(e);
                    }
                };

                dialog.Content = mainPanel;

                // 在主窗口上显示对话框
                await dialog.ShowDialog(mainWindow);
            }
            else
            {
                _logger.LogWarning("无法获取主窗口，无法显示对话框");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "显示消息对话框时发生错误");
        }
    }

    /// <summary>
    /// 释放资源
    /// </summary>
    public override void Dispose()
    {
        try
        {
            // 断开连接
            if (_tcpClientService.IsConnected)
            {
                _tcpClientService.DisconnectSync();
            }
            
            // 注销事件
            if (_tcpClientService != null)
            {
                _tcpClientService.ConnectionStateChanged -= OnConnectionStateChanged;
            }
            
            if (Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IControlledApplicationLifetime lifetime)
            {
                lifetime.Exit -= OnApplicationExit;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "释放资源时发生错误");
        }
        
        base.Dispose();
    }

    #endregion
} 